// 获取DOM元素
const daysInput = document.getElementById('days');
const hoursInput = document.getElementById('hours');
const minutesInput = document.getElementById('minutes');
const secondsInput = document.getElementById('seconds');
const timeDisplay = document.getElementById('time-display');
const startButton = document.getElementById('start');
const pauseButton = document.getElementById('pause');
const stopButton = document.getElementById('stop');

let totalSeconds = 0;  // 总计时秒数
let intervalId = null; // 计时器ID
let isPaused = false;  // 是否暂停状态
let timerHistory = JSON.parse(localStorage.getItem('timerHistory')) || [];
const historyList = document.getElementById('history-list');

// 格式化时间显示
function formatTime(totalSeconds) {
    const days = Math.floor(totalSeconds / (24 * 3600));
    const hours = Math.floor((totalSeconds % (24 * 3600)) / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;
    
    return `${days.toString().padStart(2, '0')}:${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}

// 更新按钮状态
function updateButtonStates(running) {
    startButton.disabled = running;
    pauseButton.disabled = !running;
    stopButton.disabled = !running;
    daysInput.disabled = running;
    hoursInput.disabled = running;
    minutesInput.disabled = running;
    secondsInput.disabled = running;
}

// 添加保存历史记录的函数
function saveToHistory(initialTime) {
    const historyItem = {
        id: Date.now(),
        initialTime: initialTime,
        date: new Date().toLocaleString('zh-CN')
    };
    
    timerHistory.unshift(historyItem); // 添加到数组开头
    if (timerHistory.length > 10) { // 最多保存10条记录
        timerHistory.pop();
    }
    
    localStorage.setItem('timerHistory', JSON.stringify(timerHistory));
    updateHistoryDisplay();
}

// 更新历史记录显示
function updateHistoryDisplay() {
    historyList.innerHTML = timerHistory.map(item => `
        <div class="history-item" data-id="${item.id}">
            <div class="info">
                <div class="time">${formatTime(item.initialTime)}</div>
                <div class="date">${item.date}</div>
            </div>
            <button class="delete-btn" onclick="deleteHistory(${item.id})">
                删除
            </button>
        </div>
    `).join('');
}

// 删除历史记录
function deleteHistory(id) {
    timerHistory = timerHistory.filter(item => item.id !== id);
    localStorage.setItem('timerHistory', JSON.stringify(timerHistory));
    updateHistoryDisplay();
}

// 开始计时
startButton.addEventListener('click', () => {
    if (intervalId !== null) return;
    
    const days = parseInt(daysInput.value) || 0;
    const hours = parseInt(hoursInput.value) || 0;
    const minutes = parseInt(minutesInput.value) || 0;
    const seconds = parseInt(secondsInput.value) || 0;
    
    if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) {
        alert('请输入有效的时间！');
        return;
    }
    
    totalSeconds = (days * 24 * 3600) + (hours * 3600) + (minutes * 60) + seconds;
    
    // 保存到历史记录
    saveToHistory(totalSeconds);
    
    timeDisplay.textContent = formatTime(totalSeconds);
    
    intervalId = setInterval(() => {
        if (totalSeconds <= 0) {
            clearInterval(intervalId);
            intervalId = null;
            updateButtonStates(false);
            alert('时间到！');
            return;
        }
        
        totalSeconds--;
        timeDisplay.textContent = formatTime(totalSeconds);
    }, 1000);
    
    updateButtonStates(true);
});

// 暂停计时
pauseButton.addEventListener('click', () => {
    if (isPaused) {
        // 继续计时
        intervalId = setInterval(() => {
            if (totalSeconds <= 0) {
                clearInterval(intervalId);
                intervalId = null;
                updateButtonStates(false);
                alert('时间到！');
                return;
            }
            
            totalSeconds--;
            timeDisplay.textContent = formatTime(totalSeconds);
        }, 1000);
        pauseButton.innerHTML = `
            <svg class="icon" viewBox="0 0 24 24">
                <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
            </svg>
            暂停
        `;
    } else {
        // 暂停计时
        clearInterval(intervalId);
        intervalId = null;
        pauseButton.innerHTML = `
            <svg class="icon" viewBox="0 0 24 24">
                <path d="M8 5v14l11-7z"/>
            </svg>
            继续
        `;
    }
    isPaused = !isPaused;
});

// 结束计时
stopButton.addEventListener('click', () => {
    clearInterval(intervalId);
    intervalId = null;
    isPaused = false;
    totalSeconds = 0;
    timeDisplay.textContent = '00:00:00:00';
    daysInput.value = '';
    hoursInput.value = '';
    minutesInput.value = '';
    secondsInput.value = '';
    updateButtonStates(false);
    pauseButton.innerHTML = `
        <svg class="icon" viewBox="0 0 24 24">
            <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
        </svg>
        暂停
    `;
});

// 限制输入范围
daysInput.addEventListener('input', () => {
    if (daysInput.value > 99) daysInput.value = 99;
    if (daysInput.value < 0) daysInput.value = 0;
});

hoursInput.addEventListener('input', () => {
    if (hoursInput.value > 23) hoursInput.value = 23;
    if (hoursInput.value < 0) hoursInput.value = 0;
});

minutesInput.addEventListener('input', () => {
    if (minutesInput.value > 59) minutesInput.value = 59;
    if (minutesInput.value < 0) minutesInput.value = 0;
});

secondsInput.addEventListener('input', () => {
    if (secondsInput.value > 59) secondsInput.value = 59;
    if (secondsInput.value < 0) secondsInput.value = 0;
});

// 页面加载时显示历史记录
document.addEventListener('DOMContentLoaded', () => {
    updateHistoryDisplay();
}); 